package com.jsmile.cloud.goodscenter.spu.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jsmile.cloud.goodscenter.api.enums.SaleStatusEnum;
import com.jsmile.cloud.goodscenter.spu.event.SpuEditEvent;
import com.jsmile.cloud.goodscenter.spu.model.ShopSpu;
import com.jsmile.cloud.goodscenter.spu.model.Spu;
import com.jsmile.cloud.goodscenter.spu.repo.ShopSpuRepository;
import com.jsmile.cloud.goodscenter.spu.repo.SpuRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 商品编辑后所有商户和店铺商品得下架
 */
@Slf4j
@Component
public class SpuEditListener {

    @Autowired
    private SpuRepository spuRepository;
    @Autowired
    private ShopSpuRepository shopSpuRepository;

    @Async
    @Order
    @EventListener(SpuEditEvent.class)
    public void spuPublish(SpuEditEvent event) {
        log.info("spu编辑：{}", event.getSpu());
        spuRepository.update(new UpdateWrapper<Spu>().lambda().set(Spu::getSaleStatus, SaleStatusEnum.PULL.getValue()).ne(Spu::getTenantId, event.getSpu().getTenantId())
            .eq(Spu::getSpuId, event.getSpu().getSpuId()));
        shopSpuRepository
            .update(new UpdateWrapper<ShopSpu>().lambda().set(ShopSpu::getSaleStatus, SaleStatusEnum.PULL.getValue()).eq(ShopSpu::getSpuId, event.getSpu().getSpuId()));
    }

}
